//
//  WYCompose.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/20.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit
import pop


class WYCompose: UIView {
    
    
    //储存目标控制器
    private var target: UIViewController?
    //MARK: == 懒加载控件 磨砂控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    //储存创建的额 composebutton
    private lazy var composeButtonArray = [WYComposeMenuButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        let iamge = UIImage.getScreenShot()
//        UIImagePNGRepresentation(iamge)?.writeToFile("/User/wangyi/Desktop/1.png", atomically: true)
        setUpUI()
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //这只控件
    private func setUpUI() {
      
        //背景色
        backgroundColor = RandomColor()
        frame.size = CGSize(width: ScreenWidth, height: Screenheight)
        //添加控件  磨砂图片的添加
        addSubview(bgImageView)
        //添加约束 图片的
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        
        
//        //设置 Button
//        let button = WYComposeMenuButton()
//        button.size = CGSize(width: 80, height: 110)
//        button.setImage(UIImage(named: "tabbar_compose_idea"), forState: .Normal)
//        button.setTitle("文字", forState: .Normal)
//        addSubview(button)
        childButtom()
        loadComposePlist()
        
        
        }
    func show(taget: UIViewController) {
        
        self.target = taget;
        
        target?.view.addSubview(self);
        
        
        //获取最上面的 window
        
//        let window = UIApplication.sharedApplication().windows.last!
//        window.addSubview(self)
        
        for (i, value) in composeButtonArray.enumerate() {
        
//            //开启动画
//            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
//            //动画执行目的地
//            animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: value.centerY - 350))
//            //设置弹簧效果,抖动幅度访问 range [0, 20]
//            animation.springBounciness = 8
//            //抖动的初始速度
//            animation.springSpeed = 10
//            //开始动画时间
//            animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
//            //执行动画
//            value.pop_addAnimation(animation, forKey: nil)
            startAnimation(value, i: i, isUp: true)
        }
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //数组反转 遍历的而是 Button value 是 Button  i 是为了延迟 一个延迟动画 isUp 用来判是否为
        for (i, value) in composeButtonArray.reverse().enumerate() {
            
                startAnimation(value, i: i, isUp: false)
                   }
        //延迟 返回界面
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
        
    }
    
    //开启 pop 动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //执行目的地
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        //动画执行的目的地
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        //设置弹簧效果
        animation.springBounciness = 8
        //设置弹簧速速
        animation.springSpeed = 10
        //开始动画时间
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        //执行动画
        value.pop_addAnimation(animation, forKey: nil)

    }

    //读取plist 文件
    private func  loadComposePlist() -> [WYComposeMenu] {
    
        //获取 pilst 文件
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let composeArrDic = NSArray(contentsOfFile: path!)
        
        var tempArr = [WYComposeMenu]()
        for dic in composeArrDic! {
        
            let composeNume = WYComposeMenu(dic: dic as! [String: AnyObject])
            tempArr.append(composeNume)
            
        }
        return tempArr
    }
    
    private func childButtom() {
        //按钮高度 宽度
        let buttonHeight: CGFloat = 110
        let buttonWidth: CGFloat = 80
        //按钮的间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        //获取 plist 里面的数据
        let composeMenuArray = loadComposePlist()
        
        for (i, value) in composeMenuArray.enumerate() {
        
            let button = WYComposeMenuButton()
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            //计算列数
            let ColIndex = i % 3
            let rowIndex = i / 3
            //计算x 的坐标
            
            button.x = buttonWidth * CGFloat(ColIndex) + CGFloat(ColIndex + 1) * itemMargin
            button.y = buttonHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + self.height
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            
            button.composeMenu = value
            
            //添加点击事件
            button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
            addSubview(button)
            
            //添加到全局数组中
            composeButtonArray.append(button)
            
        }
        
    }
    //MARK: -- 按钮的点击事件
    @objc private func buttonAction(button: WYComposeMenuButton) {
    
        print("点击了")
       UIView.animateWithDuration(0.25, animations: { () -> Void in
        for value in self.composeButtonArray {
        
            value.alpha = 0.2
            if value == button {
            
                //点击放大
                value.transform = CGAffineTransformMakeScale(3, 3)
            } else {
            
                //其他按钮缩小
                value.transform = CGAffineTransformMakeScale(0.4, 0.4)
            }
        }
        }) { (_) -> Void in
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                for value in self.composeButtonArray {
                
                    value.alpha = 1
                    value.transform = CGAffineTransformIdentity
                }
                }, completion: { (_) -> Void in
                    let classType = NSClassFromString(button.composeMenu!.className!) as! UIViewController.Type
           
                    print(button.composeMenu?.className);
                    
                    //创建指定对象
                    let vc = classType.init()
                    //创建导航控制器
                    let nav = UINavigationController(rootViewController: vc)
                    self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                    })
                    
            })
        }
    }
    
}
